package com.woniu.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.woniu.entity.Result;
import com.woniu.entity.dto.AdminLoginDTO;
import com.woniu.pojo.Admin;
import com.woniu.pojo.LoginLog;
import com.woniu.service.AdminService;
import com.woniu.service.ILoginLogService;
import com.woniu.utils.AddressUtils;
import com.woniu.utils.BaseController;
import com.woniu.utils.MobileUtil;
import com.woniu.utils.SMSUtils;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 何荣卓
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@Api("后台登入")
public class AdminController extends BaseController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ILoginLogService loginLogService;

    @ApiOperation("验证码方法")
    @GetMapping("/sendSms/{phone}")
    @ResponseBody
    public Result sendSms(@PathVariable  String phone, HttpSession session){
        if(!MobileUtil.checkPhone(phone)){
            return new Result(500,"手机号码错误");
        }
        String redisCodeCount = stringRedisTemplate.opsForValue().get("login_code_" + phone + "_count");
        if ("5".equals(redisCodeCount)){
            return new Result(500,"您今天发送的短信太多了");
        }
        String randomNum = SMSUtils.getRandomNum(4);
//        SMSUtils.sendSms(phone,randomNum);
        System.out.println("生成的验证码："+randomNum);
        stringRedisTemplate.opsForValue().set("login_code_" + phone, randomNum, 60, TimeUnit.SECONDS);
        if (StringUtils.isEmpty(redisCodeCount)){
            stringRedisTemplate.opsForValue().set("login_code_" + phone + "_count","1");
        }else {
            stringRedisTemplate.opsForValue().set("login_code_" + phone + "_count",Integer.parseInt(redisCodeCount) + 1 + "");
        }
        return new Result(200,"验证码发送成功");
    }



    @ApiOperation("登入方法")
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody AdminLoginDTO loginAdminDTO, HttpSession session, HttpServletResponse response){
        if (!MobileUtil.checkPhone(loginAdminDTO.getPhone())){
            return new Result(500,"手机号码错误");
        }
        String session_code = stringRedisTemplate.opsForValue().get("login_code_" + loginAdminDTO.getPhone());
        if (session_code == null){
            return new Result(500,"验证码错误");
        }
        if (!session_code.equalsIgnoreCase(loginAdminDTO.getCode())){
            return new Result(500,"验证码错误");
        }
        Admin admin = adminService.getByPhone(loginAdminDTO.getPhone());
        if (admin == null){
            return new Result(500,"该手机号用户不存在");
        }

        Cookie cookie = new Cookie("token", loginAdminDTO.getPhone());
        cookie.setPath("/");
        cookie.setDomain("localhost");
        response.addCookie(cookie);
        stringRedisTemplate.delete("login_code_" + loginAdminDTO.getPhone());
        return new Result(200,"登入成功");
    }

    @ApiOperation("密码登入")
    @PostMapping("/loginform")
    @ResponseBody
    public Result loginform(@RequestBody AdminLoginDTO adminLoginDTO,
                            HttpSession session,
                            HttpServletResponse response,
                            HttpServletRequest request) throws IOException {
        if (!MobileUtil.checkPhone(adminLoginDTO.getPhone())){
            return new Result(500,"手机号码错误");
        }
        Admin admin = adminService.getByPhoneAndPassword(adminLoginDTO);
        if (admin == null){
            return new Result(500,"该用户不存在");
        }

        Cookie cookie = new Cookie("token", adminLoginDTO.getPhone());
        cookie.setPath("/");
        cookie.setDomain("localhost");
        response.addCookie(cookie);
        stringRedisTemplate.delete("login_code_" + adminLoginDTO.getPhone());
        // 登录成功要将token数据返回给前端,response.data  你是将token设置到cookie中了，前端是从响应体里面获取token的
        Map<String, String> map = new HashMap<>();
        map.put("token", adminLoginDTO.getPhone());
        //是返回cookie吗，cookie里面包含token

        //获取登录的IP
        String loginIP = AddressUtils.getLoginIP(request);
        /**
         *获取浏览器信息;
         */
        String ua = request.getHeader("User-Agent");
        //转成UserAgent对象
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        Browser browser = userAgent.getBrowser();
        //浏览器名
        String browserInfo=browser.toString().toLowerCase();
        System.out.println("浏览器信息为"+browserInfo);
        System.out.println("ip为"+loginIP);
        // 获取地址
        String ipAddress = AddressUtils.getIpAddress(loginIP);
        System.out.println("地址为"+ipAddress);
        // 保存登录信息
        LoginLog loginLog = new LoginLog();
        loginLog.setDate(new Date());
        loginLog.setIp(loginIP);
        loginLog.setAdminId(adminService.getByPhone(adminLoginDTO.getPhone()).getId());
        loginLog.setBrowser(browserInfo);
        loginLog.setLocation(ipAddress);
        loginLogService.save(loginLog);
        return new Result(200,"登入成功", cookie);
    }

    @ApiOperation("token查询")
    @GetMapping("info")
    public Result info(String token){
        Admin admin = adminService.getByPhone(token);
        return toDataResult(admin);
    }




}
